<template>
  <div class="register">
    <el-dialog
      class="register"
      title="用户注册"
      :visible.sync="isShow"
      width="600px"
      :show-close="false"
    >
      <div slot="title" class="title">用户注册</div>

      <!-- 头像上传 -->

      <el-form :model="form" label-width="100px" :rules="rules" ref="form">
        <el-form-item label="头像" class="updata-avatar" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="baseUrl + '/uploads'"
            :show-file-list="false"
            name="image"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="baseUrl + '/' + form.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <!-- 表单组件 -->
        <el-form-item prop="username" label="昵称">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item prop="code" label="图形码">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.code"></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <img @click="changeCode" class="code-img" :src="baseUrl + codeImgUrl" alt />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item prop="rcode" label="验证码">
          <el-row>
            <el-col :span="15">
              <el-input v-model="form.rcode"></el-input>
            </el-col>
            <el-col :span="8" :offset="1">
              <!-- 3.在html上使用倒计时时间处理，当时间为6时，可以点击（disabled为true时代表禁用），倒计时过程中不可点击
                     加一个span标签用于显示倒计时，做一个v-if:倒计时过程中才显示
              -->
              <el-button @click="getRcode" :disabled="totalTime !=6" class="btn">
                获取用户验证码
                <span v-if="totalTime != 6">({{ totalTime }}s)</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <!-- 底部确定和取消按钮 -->
      <div slot="footer" class="footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 使用axios
import { getCodeApi, toRegister } from "@/api/register.js"; // 如果有多个，直接在里面添加
export default {
  watch: {
    "isShow"(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
      }
    },
  },
  data() {
    return {
      isShow: false, //是否显示对话框
      totalTime: 6, // 1.设置一个总倒计时时间
      form: {
        avatar: "", //是	string	头像地址
        username: "", //是	string	用户名
        email: "", //是	string	邮箱
        phone: "", //是	string	手机号
        password: "", //是	string	密码
        code: "",
        rcode: "", //是	string	验证码
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }], //是	string	头像地址
        username: [
          { required: true, message: "请输入用户名", trigger: "change" },
          {
            min: 1,
            max: 6,
            message: "用户名不能小于1位，不能大于6位",
            trigger: "change",
          },
        ], //是	string	用户名
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱"));
              }
            },
            trigger: "change",
          },
        ], //是	string	邮箱
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "change",
          },
        ], //是	string	手机号
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 6,
            max: 12,
            message: "密码不能小于6位，不能大于12位",
            trigger: "change",
          },
        ], //是	string	密码
        code: [
          { required: true, message: "请输入图形码", trigger: "change" },
          { min: 4, max: 4, message: "验证码必须是4位", trigger: "change" },
        ], // 图形码

        rcode: [
          { required: true, message: "请输入验证码", trigger: "change" },
          { min: 4, max: 4, message: "验证码必须是4位", trigger: "change" },
        ], //是	string	验证码
      },
      baseUrl: process.env.VUE_APP_URL,
      codeImgUrl: "/captcha?type=sendsms", // 图形码地址
    };
  },

  methods: {
    handleAvatarSuccess(res) {
      //   上传组件element没有帮我们做主动验证，需要我们手动去触发验证
      // el-form的this.validateField(["prop的值"])
      window.console.log(res);
      //   this.imageUrl = res.data.file_path
      this.form.avatar = res.data.file_path;
      //   局部验证
      this.$refs.form.validateField(["avatar"]);
      // this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          // 在验证成功后调用登录的API接口

          toRegister(this.form).then((res) => {
            window.console.log("注册的返回值", res);
            // if (res.data.code == 200) {
              this.$message.success("注册成功");
              this.isShow = false; //注册成功后关闭注册界面
            // }
          });
          // this.$message.success("验证成功");
        } 
        // else {
        //   this.$message.error("验证失败");
        // }
      }
      );
    },
    // 点击验证码切换
    changeCode() {
      this.codeImgUrl = "/captcha?type=sendsms&dfd=" + Math.random();
    },
    // 点击获取手机验证码，必须要手机号和验证码都正确才行
    // 如果验证通过，errorMessage则为空，我们定义一个num变量，当为空时.num++。如果num=2，则表示验证通过
    getRcode() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        window.console.log("手机验证校检", errorMessage);
        if (errorMessage == "") {
          num++;
        }
      });
      if (num == 2) {
        // 最新谷歌浏览器不支持带cookie，需要在main.js中的axios中使用 ithCredentials: true // 跨域带cookie到后端

        // 2. 倒计时处理 totaTime=5，写在验证通过之后，接口调用之前
        // 一秒钟执行一次-- ，如果总时间小于等于0，清除倒计时，还原总时间
        this.totalTime--; // 4.修复1秒内还是可以多次点击按钮的问题，让它一进入倒计时前就执行一个--，让时间立马倒计时，就避免了这个问题
        let _time = setInterval(() => {
          this.totalTime--;
          if (this.totalTime <= 0) {
            // 清除定时器
            clearInterval(_time);
            // 还原时间
            this.totalTime = 6;
          }
        }, 1000);

        // this.$axios({
        //   url: "/sendsms",
        //   method: "post",
        //   data: {
        //     code: this.form.code,
        //     phone: this.form.phone,
        //   },
        getCodeApi({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          // this.$message.success("验证通过");
          this.$message.success(res.data.data.captcha + ""); // 需要转字符串使用，所以拼接''
          window.console.log(res);
        });
      }
    },
  },
};
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    text-align: center;
    color: #fff;
    background: linear-gradient(to right, #01c4fa, #1294fa);
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .updata-avatar {
    text-align: center;
  }

  .code-img {
    width: 100%;
    height: 40px;
  }
  .btn {
    width: 100%;
  }

  .el-dialog_header {
    padding: 0;
  }
  .footer {
    text-align: center;
  }
}
</style>